package development.app;

import java.util.Vector;

import state.Clip;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.component.Event;
import state.component.EventListener;
import state.component.GameScrollBar;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.util.GameColor;
import state.util.Hashtable;
import state.util.ImageUtil;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.bean.AppCategory;
import development.group.FrmGroupCuaHang18PlusNapXu;

public class FrmCuaHangVas extends GameForm implements EventListener {
  public static String CUAHANG_NAME;
  public static String CUAHANG_CATEGORY_CODE;
  public static String type; // quyet dinh ve
  private String[] CAMNANG_ID;

  String[] listTypeDraw = new String[] { "drawMain", "drawCategory", "drawContentList", "drawContent" };
  private ImageText text8;
  private GameImage iconListStory;
  private int chooseIndex;
  private final int DX = 0;
  private final int DY = 25;
  private int HOZ_DISTANCE = 0;
  private int VER_DISTANCE = 46;
  int dx = 0;
  int dy = 25;
  private final int MAXROW = 5;
  private int NUMBER_OF_ITEM_PER_ROW = 1;
  private int numberOfItem;
  int step;// do dai khi cuon
  boolean isshowdetail;
  int currentpage;

  int MAXPAGE = 1;
  int totalcount;
  int countpercent;
  public int minTextY;
  private AppCategory appCategory;
  private Vector appcategoryList;

  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView; // Là khung nhìn để vẽ đoạn text ra

  private static GameForm singleton;
  private String urldownload;
  private String title;
  boolean isOnRecieveData;
  boolean isdownloaded;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmCuaHangVas();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    CAMNANG_ID = new String[] { "TV_BO_THUOC_LA", "TV_MEO_VAT", "TimYTrungNhan", "TRUYEN", "GIACMO", "TANSINHVIEN", "BOI_VUI", "CSVoChong" };
    iconListStory = ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "icon_list_story.png");
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    currentpage = 0;
    chooseIndex = 0;
    isshowdetail = false;
    totalcount = 0;
    countpercent = 100;
    dx = DX;
    dy = DY;
    step = VER_DISTANCE;
    isOnRecieveData = false;
    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10); // Là khung nhìn để vẽ đoạn text ra
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);
    NUMBER_OF_ITEM_PER_ROW = 1;
    dy = 25;
    dx = 0;
    HOZ_DISTANCE = 0;
    VER_DISTANCE = 50;
    appCategory = new AppCategory();
    appcategoryList = new Vector();
    urldownload = null;
    title = CUAHANG_NAME;
  }

  private void drawMenu(Graphics g) {
    if (type.equalsIgnoreCase(listTypeDraw[1])) {
      DrawUtils.drawTopBar(g);
      text8.drawString2(g, title, GameColor.WHITE_CODE, 10, 5, GameConstants.TOP_LEFT_ANCHOR);
      text8.drawString2(g, (currentpage + 1) + "/" + MAXPAGE + "  Trang", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 10, 5, GameConstants.TOP_RIGHT_ANCHOR);
    } else if (type.equalsIgnoreCase(listTypeDraw[2])) {
      DrawUtils.drawTopBar(g);
      text8.drawString2(g, title, GameColor.WHITE_CODE, 10, 5, GameConstants.TOP_LEFT_ANCHOR);
      text8.drawString2(g, (currentpage + 1) + "/" + MAXPAGE + "  Trang", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 10, 5, GameConstants.TOP_RIGHT_ANCHOR);
    } else if (type.equalsIgnoreCase(listTypeDraw[3])) {
      DrawUtils.drawTopBar(g);
      text8.drawString2(g, appCategory.getName(), GameColor.WHITE_CODE, 10, 5, GameConstants.TOP_LEFT_ANCHOR);
    }
    if (countpercent < 100) {
      DrawUtils.setBottomBar(_manager, "", countpercent + "%", "Trở về");
    } else {
      if (type.equalsIgnoreCase(listTypeDraw[3])) {
        DrawUtils.setBottomBar(_manager, "", "", "Trở về");
      } else {
        DrawUtils.setBottomBar(_manager, "", "Chọn", "Trở về");
      }
    }
  }

  private void drawCategory(Graphics g) {
    if (isOnRecieveData) {
      if (!appcategoryList.isEmpty()) {
        for (int row = 0; row < appcategoryList.size(); row++) {
          int x = dx + HOZ_DISTANCE * (row % NUMBER_OF_ITEM_PER_ROW);
          int y = dy + VER_DISTANCE * (row / NUMBER_OF_ITEM_PER_ROW);
          if (row == chooseIndex) {
            g.setColor(0x4EA2D0);
            g.fillRect(x, y, GameConstants.SCREEN_WIDTH, VER_DISTANCE);
          }
          g.drawImage(iconListStory, x + 24, y + 13, GameConstants.CENTER_ANCHOR);
          appCategory = (AppCategory) appcategoryList.elementAt(row);
          text8.drawParagraph2(g, appCategory.getName(), GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 40, x + 38, y + 6, scrollBar);
          g.setColor(0xC0C0C0);
          g.drawLine(0, y + VER_DISTANCE, GameConstants.SCREEN_WIDTH, y + VER_DISTANCE);
        }
        scrollBar.draw(g);
      } else {
        if (numberOfItem == 0) {
          countpercent = 100;
        }
      }
    }
  }

  private void drawContentList(Graphics g) {
    if (isOnRecieveData) {
      if (!appcategoryList.isEmpty()) {
        for (int row = 0; row < numberOfItem; row++) {
          int x = dx + HOZ_DISTANCE * (row % NUMBER_OF_ITEM_PER_ROW);
          int y = dy + VER_DISTANCE * (row / NUMBER_OF_ITEM_PER_ROW);
          if (row == chooseIndex) {
            g.setColor(0x4EA2D0);
            g.fillRect(x, y, GameConstants.SCREEN_WIDTH, VER_DISTANCE);
          }
          appCategory = (AppCategory) appcategoryList.elementAt(row);
          g.drawImage(iconListStory, x + 24, y + 13, GameConstants.CENTER_ANCHOR);
          text8.drawParagraph2(g, appCategory.getName(), GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 40, x + 38, y + 6, scrollBar);
          g.setColor(0xC0C0C0);
          g.drawLine(0, y + VER_DISTANCE, GameConstants.SCREEN_WIDTH, y + VER_DISTANCE);
        }
        scrollBar.draw(g);
      } else {
        if (numberOfItem == 0) {
          countpercent = 100;
        }
      }
    }
  }

  private void drawContentData(Graphics g) {
    int x = dx;
    int y = dy;
    step = y;
    step = text8.drawParagraph2(g, appCategory.getValue(), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 40, x + 8, step + 6, scrollBar);
    scrollBar.draw(g);
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    _manager.enableTouchPad();
    DrawUtils.drawTopBar(g);
    if (type.equalsIgnoreCase(listTypeDraw[1])) {
      drawCategory(g);
    }
    if (type.equalsIgnoreCase(listTypeDraw[2]))
      drawContentList(g);
    if (type.equalsIgnoreCase(listTypeDraw[3]))
      drawContentData(g);

    drawMenu(g);
  }

  public void keyReleased(int keyCode) {

    switch (keyCode) {
    case Key.DOWN:
      chooseIndex = (chooseIndex + NUMBER_OF_ITEM_PER_ROW > numberOfItem - 1) ? chooseIndex : chooseIndex + NUMBER_OF_ITEM_PER_ROW;
      if (!type.equalsIgnoreCase(listTypeDraw[0])) {
        if (type.equalsIgnoreCase(listTypeDraw[3])) {
          if (step > GameConstants.SCREEN_HEIGHT - 50)
            dy -= VER_DISTANCE;
        } else {
          int down = dy + VER_DISTANCE * chooseIndex;
          if (down > GameConstants.SCREEN_HEIGHT - (50 + DrawUtils.getBottomBarHeight() + 25))
            dy -= VER_DISTANCE;
        }
      }
      break;
    case Key.UP:
      chooseIndex = (chooseIndex - NUMBER_OF_ITEM_PER_ROW < 0) ? chooseIndex : chooseIndex - NUMBER_OF_ITEM_PER_ROW;
      if (!type.equalsIgnoreCase(listTypeDraw[0])) {
        int up = dy + VER_DISTANCE * chooseIndex;
        if (up < 25)
          dy += VER_DISTANCE;
      }
      break;
    case Key.LEFT:
      if (type.equalsIgnoreCase(listTypeDraw[0])) {
        chooseIndex = (chooseIndex - 1 < 0) ? 0 : chooseIndex - 1;
      } else {
        if (!isshowdetail) {
          chooseIndex = 0;
          currentpage--;
          if (currentpage < 0) {
            currentpage = 0;
          } else {
            Update();
            Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
          }
        }
      }
      break;
    case Key.RIGHT:
      if (type.equalsIgnoreCase(listTypeDraw[0])) {
        chooseIndex = (chooseIndex + 1 > numberOfItem) ? numberOfItem : chooseIndex + 1;
      } else {
        if (!isshowdetail) {
          chooseIndex = 0;
          currentpage++;
          if (currentpage > MAXPAGE - 1) {
            currentpage = MAXPAGE - 1;
          } else {
            Update();
            Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
          }
        }
      }
      break;
    case Key.FIRE:
      choose(chooseIndex);
      break;
    case Key.SOFT_RIGHT:
      back();
      break;
    }
  }

  private void back() {
    if (appcategoryList.size() == 0) {
      GameGlobal.nextState(FrmGroupCuaHang18PlusNapXu.instance(), null);
      return;
    }

    if (type.equalsIgnoreCase(listTypeDraw[0])) {
      GameGlobal.nextState(FrmGroupCuaHang18PlusNapXu.instance(), null);
    } else if (type.equalsIgnoreCase(listTypeDraw[1])) {
      appCategory = (AppCategory) appcategoryList.elementAt(0);
      if (appCategory.getParentID().equalsIgnoreCase("TRUYEN") || appCategory.getParentID().equalsIgnoreCase("TV_MEO_VAT") || appCategory.getParentID().equalsIgnoreCase("BOI_VUI")) {
        GameGlobal.nextState(FrmGroupCuaHang18PlusNapXu.instance(), null);
      } else {
        DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_VAS_CATEGORY_PARENT_LIST_REQUEST);
        dataPackage.putString(appCategory.getParentID());
        dataPackage.putInt(0);
        dataPackage.putInt(MAXROW);
        Global.appClient.write(dataPackage);
        numberOfItem = 0;
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        isOnRecieveData = false;
      }
      appcategoryList = new Vector();
      chooseIndex = 0;
      dx = DX;
      dy = DY;
      currentpage = 0;
    } else if (type.equalsIgnoreCase(listTypeDraw[2])) {
      if (!appCategory.getParentID().equalsIgnoreCase("TV_BO_THUOC_LA")) {
        DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_VAS_CATEGORY_PARENT_LIST_REQUEST);
        dataPackage.putString(appCategory.getParentID());
        dataPackage.putInt(0);
        dataPackage.putInt(MAXROW);
        Global.appClient.write(dataPackage);
        appcategoryList = new Vector();
        numberOfItem = 0;
        type = listTypeDraw[1];
        dx = DX;
        dy = DY;
        chooseIndex = 0;
        isOnRecieveData = false;
        
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
      } else {
        GameGlobal.nextState(FrmGroupCuaHang18PlusNapXu.instance(), null);
      }
      currentpage = 0;
    }
    if (type.equalsIgnoreCase(listTypeDraw[3])) {
      type = listTypeDraw[2];
      dx = DX;
      dy = DY;
      isshowdetail = false;
    }
  }

  private void choose(int choosedIndex) {
    if (type.equalsIgnoreCase(listTypeDraw[0])) {
      if (choosedIndex < 3) {
        DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_VAS_CATEGORY_LIST_REQUEST);
        dataPackage.putString(CAMNANG_ID[choosedIndex]);
        dataPackage.putInt(0);
        dataPackage.putInt(MAXROW);
        Global.appClient.write(dataPackage);
        countpercent = 0;
        chooseIndex = 0;
        numberOfItem = 0;
        type = listTypeDraw[1];
        currentpage = 0;
        appcategoryList = new Vector();
        isOnRecieveData = false;
      } else if (choosedIndex == 3) {
        DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_VAS_CONTENT_LIST_REQUEST);
        dataPackage.putString("TV_BO_THUOC_LA");
        dataPackage.putInt(0);
        dataPackage.putInt(MAXROW);
        Global.appClient.write(dataPackage);
        type = listTypeDraw[2];
        countpercent = 0;
        chooseIndex = 0;
        numberOfItem = 0;
        currentpage = 0;
        appcategoryList = new Vector();
        isOnRecieveData = false;
      }
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
    } else if (type.equalsIgnoreCase(listTypeDraw[1])) {
      appCategory = (AppCategory) appcategoryList.elementAt(choosedIndex);
      if (appCategory.getHadChild().equalsIgnoreCase("0")) {
        DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_VAS_CONTENT_LIST_REQUEST);
        dataPackage.putString(appCategory.getID());
        dataPackage.putInt(0);
        dataPackage.putInt(MAXROW);
        Global.appClient.write(dataPackage);
        type = listTypeDraw[2];
        countpercent = 0;
        chooseIndex = 0;
        numberOfItem = 0;
        currentpage = 0;
        appcategoryList = new Vector();
      } else {
        DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_VAS_CATEGORY_LIST_REQUEST);
        dataPackage.putString(appCategory.getID());
        dataPackage.putInt(currentpage);
        dataPackage.putInt(MAXROW);
        Global.appClient.write(dataPackage);
        appcategoryList = new Vector();
        countpercent = 0;
        chooseIndex = 0;
        numberOfItem = 0;
        currentpage = 0;
      }
      isOnRecieveData = false;
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
    } else if (type.equalsIgnoreCase(listTypeDraw[2])) {
      appCategory = (AppCategory) appcategoryList.elementAt(chooseIndex);
      type = listTypeDraw[3];
      dx = DX;
      dy = DY;
      isshowdetail = true;
    }
  }

  private void Update() {
    dx = DX;
    dy = DY;
    countpercent = 0;
    numberOfItem = 0;
    chooseIndex = 0;
    appcategoryList = new Vector();
    if (type.equalsIgnoreCase(listTypeDraw[1])) {
      DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_VAS_CATEGORY_LIST_REQUEST);
      dataPackage.putString(appCategory.getParentID());
      dataPackage.putInt(currentpage);
      dataPackage.putInt(MAXROW);
      Global.appClient.write(dataPackage);
    }
    if (type.equalsIgnoreCase(listTypeDraw[2])) {
      DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_VAS_CONTENT_LIST_REQUEST);
      dataPackage.putString(appCategory.getParentID());
      dataPackage.putInt(currentpage);
      dataPackage.putInt(MAXROW);
      Global.appClient.write(dataPackage);
    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    GameGlobal.systemCanvas.hideAlert();
    switch (header) {
    case FrmCuaHang.GET_VAS_COUNT_RESPONSE:
      totalcount = dataPackage.nextInt();
      MAXPAGE = (int) Math.ceil((float) totalcount / (float) MAXROW);
      break;
    case FrmCuaHang.GET_VAS_CATEGORY_LIST_RESPONSE:
      AppCategory cate = new AppCategory();
      cate.setID(dataPackage.nextString());
      cate.setName(dataPackage.nextString());
      cate.setParentID(dataPackage.nextString());
      cate.setParentName(dataPackage.nextString());
      cate.setHadChild(dataPackage.nextString());
      countpercent = dataPackage.nextInt();
      appcategoryList.addElement(cate);
      numberOfItem = appcategoryList.size();
      if (cate.getParentName().length() > 15) {
        title = cate.getParentName().substring(0, 15) + "... ";
      } else
        title = cate.getParentName();
      isOnRecieveData = true;
      break;
    case FrmCuaHang.GET_VAS_CATEGORY_PARENT_LIST_RESPONSE:
      AppCategory cate_parent = new AppCategory();
      cate_parent.setID(dataPackage.nextString());
      cate_parent.setName(dataPackage.nextString());
      cate_parent.setParentID(dataPackage.nextString());
      cate_parent.setParentName(dataPackage.nextString());
      cate_parent.setHadChild(dataPackage.nextString());
      countpercent = dataPackage.nextInt();
      appcategoryList.addElement(cate_parent);
      numberOfItem = appcategoryList.size();
      if (cate_parent.getParentName().length() > 15) {
        title = cate_parent.getParentName().substring(0, 15) + "... ";
      } else
        title = cate_parent.getParentName();
      isOnRecieveData = true;
      break;
    case FrmCuaHang.GET_VAS_CONTENT_LIST_RESPONSE:
      AppCategory contentlist = new AppCategory();
      contentlist.setID(dataPackage.nextString());
      contentlist.setName(dataPackage.nextString());
      contentlist.setParentID(dataPackage.nextString());
      contentlist.setParentName(dataPackage.nextString());
      contentlist.setValue(dataPackage.nextString());
      countpercent = dataPackage.nextInt();
      appcategoryList.addElement(contentlist);
      numberOfItem = appcategoryList.size();
      if (contentlist.getParentName().length() > 15) {
        title = contentlist.getParentName().substring(0, 15) + "... ";
      } else
        title = contentlist.getParentName();
      isOnRecieveData = true;
      break;
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 50 && eventType == GameAlert.YES_BUTTON) {
      doDownload(urldownload);
    }
  }

  public void doDownload(String url) {
    Global.systemCanvas.getMidlet().platformRequest(url);
  }

  public void destroy() {
    text8 = null;
  }

  public void onActionPerform(Event event) {
  }
}